const http = require("http")
const fs = require("fs")
const qs = require("querystring")
http.createServer((req, res) => {
    if (req.url !== "/favicon.ico") {
        if (req.url.includes("/api")) {
            dataRequire(req, res)
        } else {
            fileRequire(req, res);
        }
    }
}).listen(3000, () => {
    console.log("服务器开启成功，地址为：http://localhost:3000")
})

function dataRequire(req, res) {
    let str = "";
    req.on("data", (chunk) => {
        str += chunk;
    })
    req.on("end", () => {
        let data;
        if (str) {
            data = qs.parse(str);
        } else {
            const urlObj = new URL("http://localhost:3000" + req.url);
            data = qs.parse(urlObj.search.slice(1));
        }
        // 1. 过滤前端请求，判断请求功能
        switch ((data.type).split("?")[0]) {
            case "getGoods":
                // 获取数据
                getGoods(req, res); break;
            case "login":
                // 登入
                login(req, res, data); break;
            case "register":
                // 注册
                register(req, res, data); break;
        }
    })
}
function login(req, res, data) {
    // 登入
    username = data.username;
    password = data.password;
    let str = { username, password };
    fs.readFile("./www/data/userMsg.json", "utf-8", (err, data) => {
        if (err) {
            console.log("读取失败")
        } else {
            let i = 0
            all = JSON.parse(data)
            let flag = all.some((val, idx) => {
                i = idx;
                return val.username === str.username
            })
            let msg = {}
            if (flag) {
                if (all[i].password === str.password) {
                    // - 是，返回登录成功
                    msg.code = 1;
                    msg.title = "登录成功";
                    msg.data = all[i];
                } else {
                    // - 否，返回密码不对
                    msg.code = 0;
                    msg.title = "密码不对";
                    msg.data = {};
                }
            } else {
                // - 否，返回用户名不存在
                msg.code = 2;
                msg.title = "用户名不存在";
                msg.data = {};
            }
            res.write(JSON.stringify(msg));
            res.end();
        }
    })
}

// 注册
function register(req, res, data) {
    username = data.username;
    password = data.password;
    let str = { username, password }
    //先读取
    fs.readFile("./www/data/userMsg.json", "utf-8", (err, data) => {
        if (err) {
            console.log("读取失败")
        } else {
            let arr = data ? JSON.parse(data) : [];
            let flag = arr.some(val => {
                return val.username === str.username
            })
            let msg = {};
            if (flag) {
                msg.code = 0;
                msg.title = "注册失败，用户名重复";
            } else {
                arr.push(str)
                fs.writeFile("./www/data/userMsg.json", JSON.stringify(arr), err => {
                    if (err) {
                        console.log("插入失败")
                    }
                    // 返回注册成功
                    msg.code = 1;
                    msg.title = "注册成功";
                })
            }
            res.write(JSON.stringify(msg));
            res.end()
        }
    })
}

//商品数据
function getGoods(req, res, data) {
    fs.readFile("./www/data/pag1goods.json", (err, data) => {
        res.write(data);
        res.end();
    })
}

//寻找文件
function fileRequire(req, res) {
    fs.readFile("./www" + req.url.split("?").slice(0, 1), (err, data) => {
        if (err) {
            res.write("404");
        } else {
            res.write(data);
        }
        res.end();
    })
}
